<template>
  <div class="exam-add">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>创建考试</span>
          <el-button @click="handleBack">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="exam-form"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-form-item label="考试名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入考试名称" />
        </el-form-item>

        <el-form-item label="考试说明" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入考试说明"
          />
        </el-form-item>

        <el-form-item label="考试时间" prop="examTime">
          <el-date-picker
            v-model="formData.examTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
            @change="handleExamTimeChange"
          />
        </el-form-item>

        <el-form-item label="考试时长" prop="duration">
          <el-input-number
            v-model="formData.duration"
            :min="1"
            :max="480"
            :step="5"
            :precision="0"
          />
          <span class="unit">分钟</span>
        </el-form-item>

        <el-form-item label="总分" prop="totalPoints">
          <el-input-number
            v-model="formData.totalPoints"
            :min="1"
            :max="1000"
            :step="1"
            :precision="0"
          />
          <span class="unit">分</span>
        </el-form-item>

        <el-form-item label="及格分数" prop="passScore">
          <el-input-number
            v-model="formData.passScore"
            :min="0"
            :max="formData.totalPoints"
            :step="1"
            :precision="0"
          />
          <span class="unit">分</span>
        </el-form-item>

        <!-- 防作弊设置 -->
        <el-divider content-position="left">防作弊设置</el-divider>
        <el-form-item label="防作弊等级" prop="antiCheatingLevel">
          <el-radio-group v-model="formData.antiCheatingLevel">
            <el-radio :label="0">无</el-radio>
            <el-radio :label="1">低</el-radio>
            <el-radio :label="2">中</el-radio>
            <el-radio :label="3">高</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 高级设置 -->
        <el-divider content-position="left">高级设置</el-divider>
        <el-form-item label="允许重考" prop="allowRetake">
          <el-switch v-model="formData.allowRetake" />
        </el-form-item>

        <el-form-item label="自动评分" prop="autoGrade">
          <el-switch v-model="formData.autoGrade" />
        </el-form-item>

        <el-form-item label="显示答案" prop="showAnswer">
          <el-switch v-model="formData.showAnswer" />
        </el-form-item>

        <el-form-item label="人脸验证" prop="faceVerification">
          <el-switch v-model="formData.faceVerification" />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">创建考试</el-button>
          <el-button @click="handleBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
// Remove axios import
// import axios from 'axios'

// Import API function
import { createExam } from '@/api/exam'

const router = useRouter()
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  title: '',
  description: '',
  examTime: [] as string[],
  duration: 120,
  totalPoints: 100,
  passScore: 60,
  antiCheatingLevel: 2,
  allowRetake: false,
  autoGrade: true,
  showAnswer: false,
  faceVerification: false
})

// 默认时间
const defaultTime = [
  new Date(2000, 1, 1, 9, 0, 0),
  new Date(2000, 1, 1, 11, 0, 0)
]

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入考试名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入考试说明', trigger: 'blur' }
  ],
  examTime: [
    { required: true, message: '请选择考试时间', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入考试时长', trigger: 'blur' }
  ],
  totalPoints: [
    { required: true, message: '请输入总分', trigger: 'blur' }
  ],
  passScore: [
    { required: true, message: '请输入及格分数', trigger: 'blur' }
  ],
  antiCheatingLevel: [
    { required: true, message: '请选择防作弊等级', trigger: 'change' }
  ]
})

// 处理考试时间变化
const handleExamTimeChange = (val: string[]) => {
  if (val && val.length === 2) {
    const start = new Date(val[0])
    const end = new Date(val[1])
    const duration = Math.floor((end.getTime() - start.getTime()) / (1000 * 60))
    formData.duration = duration
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      const data = {
        title: formData.title,
        description: formData.description,
        startTime: formData.examTime[0],
        endTime: formData.examTime[1],
        duration: formData.duration,
        totalPoints: formData.totalPoints,
        passScore: formData.passScore,
        antiCheatingLevel: formData.antiCheatingLevel,
        allowRetake: formData.allowRetake ? 1 : 0,
        autoGrade: formData.autoGrade ? 1 : 0,
        showAnswer: formData.showAnswer ? 1 : 0,
        faceVerification: formData.faceVerification ? 1 : 0
      }
      createExam(data)
        .then(() => {
          ElMessage.success('创建成功')
          router.push('/main/exam')
        })
        .catch((error) => {
          console.error('创建考试失败:', error)
          ElMessage.error('创建考试失败')
        })
    } else {
      console.log('验证失败：', fields)
    }
  })
}

// 返回
const handleBack = () => {
  router.push('/main/exam')
}
</script>

<style scoped>
.exam-add {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
}

:deep(.el-card) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.exam-form {
  max-width: 800px;
  margin: 0 auto;
}

.unit {
  margin-left: 10px;
  color: #666;
}

:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: bold;
}

:deep(.el-form-item__label) {
  color: #606266;
}

:deep(.el-form-item__content) {
  color: #303133;
}

:deep(.el-button--small) {
  padding: 4px 8px;
}
</style>
